package com.sam.book.tree;


/**
 * 经典树
 * Created by samwang on 2017/12/22.
 */
public class ClassicalTree {
    public static void main(String[] args) {
        TreeNode root = new TreeNode();
        root.element = "根";

        TreeNode child1 = new TreeNode();
        child1.element = "子1";
        root.firstChild = child1;

        TreeNode child2 = new TreeNode();
        child2.element = "子2";
        child1.nextSibling = child2;

        TreeNode grandchild1 = new TreeNode();
        grandchild1.element = "孙11";
        child1.firstChild = grandchild1;

        TreeNode grandchild21 = new TreeNode();
        grandchild21.element = "孙21";
        child2.firstChild = grandchild21;

        TreeNode grandchild22 = new TreeNode();
        grandchild22.element = "孙22";
        grandchild21.nextSibling = grandchild22;

        System.out.println("---先序----");
        preorder(root);
        System.out.println("----后序-----");
        postorder(root);
    }


    public static void preorder(TreeNode node) {
        System.out.println(node.element);
        if (node.firstChild != null) {
            preorder(node.firstChild);
        }
        if (node.nextSibling != null) {
            preorder(node.nextSibling);
        }
    }

    static void postorder(TreeNode node) {
        if (node.firstChild != null) {
            postorder(node.firstChild);
        }
        System.out.println(node.element);
        if (node.nextSibling != null) {
            postorder(node.nextSibling);
        }
    }



}

class TreeNode {
    Object element;
    TreeNode firstChild;
    TreeNode nextSibling;
}
